package com.neo.utils;

import java.io.Serializable;
import java.util.Collection;
import java.util.LinkedList;
import java.util.List;
import org.apache.commons.lang3.SerializationUtils;
import org.apache.shiro.codec.Base64;
import org.apache.shiro.session.Session;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;

public class SerializeUtils extends SerializationUtils{
	
	private static Logger logger = LoggerFactory.getLogger(SerializeUtils.class);
	
	/**
	 * 先序列化，再使用Base64加码
	 * @param obj
	 * @return 
	 */
	public static String serializeToString(Serializable obj) {
		if (!StringUtils.isEmpty(obj)) {
			byte[] bs = serialize(obj);
			return Base64.encodeToString(bs);
		}else {
			logger.warn("input serializable is null, return null");
		}
		return null;
	}
	
	/**
	 * 使用Base64解码，再反序列化
	 * @param base64
	 * @return
	 */
	public static Session dserializeToObject(String base64) {
		if (!StringUtils.isEmpty(base64)) {
			byte[] bs = Base64.decode(base64);
			return deserialize(bs);
		}else {
			logger.warn("input serializable is null, return null");
		}
		return null;
	}

	public static <T> Collection<T> deserializeFromStringController(Collection<String> base64s) {
        try {
            List<T> list = new LinkedList<T>();
            for (String base64 : base64s) {
                byte[] objectData = Base64.decode(base64);
                T t = deserialize(objectData);
                list.add(t);
            }
            return list;
        } catch (Exception e) {
            throw new RuntimeException("deserialize session error", e);
        }
    }
	
}
